package mc747.servicos.clientes;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;

public class Builder {


	public static Cliente consultaDados(int cpf) {
		HttpClient client = new HttpClient();
		String xml = new String();
		String[] response;
		Cliente c = new Cliente();
		
		String params = cpf + ".xml";
		GetMethod method = new GetMethod(
				"http://mc747-clientes.heroku.com/clientes/" + params);

		try {
			System.err.println("Method: " + method.getURI());
		} catch (URIException e1) {
			e1.printStackTrace();
		}

		//envia o request
		try {
			client.executeMethod(method);
			System.err.println("response: " + method.getResponseBodyAsString());
			
			//formata o xml para ser tratado corretamente
			response = method.getResponseBodyAsString().split("\n");
			response[3] = "";
			response[8] = "";
			response[11] = response[11].replace("-", "");

			for(int y = 0 ; y < response.length ; y++){
				xml = xml + response[y];
			}
			
			//pege os dados do xml usando XStream
			XStream x = new XStream();
			x.alias("cliente", Cliente.class);
	        c = (Cliente) x.fromXML(xml);
	 
/*impressao para conferir os resultados
	        System.out.println(c.getId());
	        System.out.println(c.getNome());
	        System.out.println(c.getCpf());
	        System.out.println(c.getDatanascimento());
	        System.out.println(c.getCep());
	        System.out.println(c.getComplemento());
	        System.out.println(c.getDdd());
	        System.out.println(c.getTelefone());
	        System.out.println(c.getEmail());
*/
		} catch (Exception e) {
			System.err.println(e);
		}
		method.releaseConnection();
		return c;
	 
	}
}
